home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_emacs.idb / usr / freeware / info / cl-3.z / cl-3 (.txt)
GNU Info File  |  1998-10-27  |  51KB  |  898 lines

  1. This is Info file ../info/cl, produced by Makeinfo-1.64 from the input
  2. file cl.texi.
  3.    This file documents the GNU Emacs Common Lisp emulation package.
  4.    Copyright (C) 1993 Free Software Foundation, Inc.
  5.    Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.    Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the section entitled "GNU General Public License" is included
  11. exactly as in the original, and provided that the entire resulting
  12. derived work is distributed under the terms of a permission notice
  13. identical to this one.
  14.    Permission is granted to copy and distribute translations of this
  15. manual into another language, under the above conditions for modified
  16. versions, except that the section entitled "GNU General Public License"
  17. may be included in a translation approved by the author instead of in
  18. the original English.
  19. File: cl,  Node: For Clauses,  Next: Iteration Clauses,  Prev: Loop Examples,  Up: Loop Facility
  20. For Clauses
  21. -----------
  22. Most loops are governed by one or more `for' clauses.  A `for' clause
  23. simultaneously describes variables to be bound, how those variables are
  24. to be stepped during the loop, and usually an end condition based on
  25. those variables.
  26.    The word `as' is a synonym for the word `for'.  This word is
  27. followed by a variable name, then a word like `from' or `across' that
  28. describes the kind of iteration desired.  In Common Lisp, the phrase
  29. `being the' sometimes precedes the type of iteration; in this package
  30. both `being' and `the' are optional.  The word `each' is a synonym for
  31. `the', and the word that follows it may be singular or plural:  `for x
  32. being the elements of y' or `for x being each element of y'.  Which
  33. form you use is purely a matter of style.
  34.    The variable is bound around the loop as if by `let':
  35.      (setq i 'happy)
  36.      (loop for i from 1 to 10 do (do-something-with i))
  37.      i
  38.           => happy
  39. `for VAR from EXPR1 to EXPR2 by EXPR3'
  40.      This type of `for' clause creates a counting loop.  Each of the
  41.      three sub-terms is optional, though there must be at least one
  42.      term so that the clause is marked as a counting clause.
  43.      The three expressions are the starting value, the ending value, and
  44.      the step value, respectively, of the variable.  The loop counts
  45.      upwards by default (EXPR3 must be positive), from EXPR1 to EXPR2
  46.      inclusively.  If you omit the `from' term, the loop counts from
  47.      zero; if you omit the `to' term, the loop counts forever without
  48.      stopping (unless stopped by some other loop clause, of course); if
  49.      you omit the `by' term, the loop counts in steps of one.
  50.      You can replace the word `from' with `upfrom' or `downfrom' to
  51.      indicate the direction of the loop.  Likewise, you can replace
  52.      `to' with `upto' or `downto'.  For example, `for x from 5 downto
  53.      1' executes five times with `x' taking on the integers from 5 down
  54.      to 1 in turn.  Also, you can replace `to' with `below' or `above',
  55.      which are like `upto' and `downto' respectively except that they
  56.      are exclusive rather than inclusive limits:
  57.           (loop for x to 10 collect x)
  58.                => (0 1 2 3 4 5 6 7 8 9 10)
  59.           (loop for x below 10 collect x)
  60.                => (0 1 2 3 4 5 6 7 8 9)
  61.      The `by' value is always positive, even for downward-counting
  62.      loops.  Some sort of `from' value is required for downward loops;
  63.      `for x downto 5' is not a legal loop clause all by itself.
  64. `for VAR in LIST by FUNCTION'
  65.      This clause iterates VAR over all the elements of LIST, in turn.
  66.      If you specify the `by' term, then FUNCTION is used to traverse
  67.      the list instead of `cdr'; it must be a function taking one
  68.      argument.  For example:
  69.           (loop for x in '(1 2 3 4 5 6) collect (* x x))
  70.                => (1 4 9 16 25 36)
  71.           (loop for x in '(1 2 3 4 5 6) by 'cddr collect (* x x))
  72.                => (1 9 25)
  73. `for VAR on LIST by FUNCTION'
  74.      This clause iterates VAR over all the cons cells of LIST.
  75.           (loop for x on '(1 2 3 4) collect x)
  76.                => ((1 2 3 4) (2 3 4) (3 4) (4))
  77.      With `by', there is no real reason that the `on' expression must
  78.      be a list.  For example:
  79.           (loop for x on first-animal by 'next-animal collect x)
  80.      where `(next-animal x)' takes an "animal" X and returns the next
  81.      in the (assumed) sequence of animals, or `nil' if X was the last
  82.      animal in the sequence.
  83. `for VAR in-ref LIST by FUNCTION'
  84.      This is like a regular `in' clause, but VAR becomes a `setf'-able
  85.      "reference" onto the elements of the list rather than just a
  86.      temporary variable.  For example,
  87.           (loop for x in-ref my-list do (incf x))
  88.      increments every element of `my-list' in place.  This clause is an
  89.      extension to standard Common Lisp.
  90. `for VAR across ARRAY'
  91.      This clause iterates VAR over all the elements of ARRAY, which may
  92.      be a vector or a string.
  93.           (loop for x across "aeiou"
  94.                 do (use-vowel (char-to-string x)))
  95. `for VAR across-ref ARRAY'
  96.      This clause iterates over an array, with VAR a `setf'-able
  97.      reference onto the elements; see `in-ref' above.
  98. `for VAR being the elements of SEQUENCE'
  99.      This clause iterates over the elements of SEQUENCE, which may be a
  100.      list, vector, or string.  Since the type must be determined at
  101.      run-time, this is somewhat less efficient than `in' or `across'.
  102.      The clause may be followed by the additional term `using (index
  103.      VAR2)' to cause VAR2 to be bound to the successive indices
  104.      (starting at 0) of the elements.
  105.      This clause type is taken from older versions of the `loop' macro,
  106.      and is not present in modern Common Lisp.  The `using (sequence
  107.      ...)' term of the older macros is not supported.
  108. `for VAR being the elements of-ref SEQUENCE'
  109.      This clause iterates over a sequence, with VAR a `setf'-able
  110.      reference onto the elements; see `in-ref' above.
  111. `for VAR being the symbols [of OBARRAY]'
  112.      This clause iterates over symbols, either over all interned symbols
  113.      or over all symbols in OBARRAY.  The loop is executed with VAR
  114.      bound to each symbol in turn.  The symbols are visited in an
  115.      unspecified order.
  116.      As an example,
  117.           (loop for sym being the symbols
  118.                 when (fboundp sym)
  119.                 when (string-match "^map" (symbol-name sym))
  120.                 collect sym)
  121.      returns a list of all the functions whose names begin with `map'.
  122.      The Common Lisp words `external-symbols' and `present-symbols' are
  123.      also recognized but are equivalent to `symbols' in Emacs Lisp.
  124.      Due to a minor implementation restriction, it will not work to have
  125.      more than one `for' clause iterating over symbols, hash tables,
  126.      keymaps, overlays, or intervals in a given `loop'.  Fortunately,
  127.      it would rarely if ever be useful to do so.  It *is* legal to mix
  128.      one of these types of clauses with other clauses like `for ... to'
  129.      or `while'.
  130. `for VAR being the hash-keys of HASH-TABLE'
  131.      This clause iterates over the entries in HASH-TABLE.  For each
  132.      hash table entry, VAR is bound to the entry's key.  If you write
  133.      `the hash-values' instead, VAR is bound to the values of the
  134.      entries.  The clause may be followed by the additional term `using
  135.      (hash-values VAR2)' (where `hash-values' is the opposite word of
  136.      the word following `the') to cause VAR and VAR2 to be bound to the
  137.      two parts of each hash table entry.
  138. `for VAR being the key-codes of KEYMAP'
  139.      This clause iterates over the entries in KEYMAP.  In GNU Emacs 18
  140.      and 19, keymaps are either alists or vectors, and key-codes are
  141.      integers or symbols.  In Lucid Emacs 19, keymaps are a special new
  142.      data type, and key-codes are symbols or lists of symbols.  The
  143.      iteration does not enter nested keymaps or inherited (parent)
  144.      keymaps.  You can use `the key-bindings' to access the commands
  145.      bound to the keys rather than the key codes, and you can add a
  146.      `using' clause to access both the codes and the bindings together.
  147. `for VAR being the key-seqs of KEYMAP'
  148.      This clause iterates over all key sequences defined by KEYMAP and
  149.      its nested keymaps, where VAR takes on values which are strings in
  150.      Emacs 18 or vectors in Emacs 19.  The strings or vectors are
  151.      reused for each iteration, so you must copy them if you wish to
  152.      keep them permanently.  You can add a `using (key-bindings ...)'
  153.      clause to get the command bindings as well.
  154. `for VAR being the overlays [of BUFFER] ...'
  155.      This clause iterates over the Emacs 19 "overlays" or Lucid Emacs
  156.      "extents" of a buffer (the clause `extents' is synonymous with
  157.      `overlays').  Under Emacs 18, this clause iterates zero times.  If
  158.      the `of' term is omitted, the current buffer is used.  This clause
  159.      also accepts optional `from POS' and `to POS' terms, limiting the
  160.      clause to overlays which overlap the specified region.
  161. `for VAR being the intervals [of BUFFER] ...'
  162.      This clause iterates over all intervals of a buffer with constant
  163.      text properties.  The variable VAR will be bound to conses of
  164.      start and end positions, where one start position is always equal
  165.      to the previous end position.  The clause allows `of', `from',
  166.      `to', and `property' terms, where the latter term restricts the
  167.      search to just the specified property.  The `of' term may specify
  168.      either a buffer or a string.  This clause is useful only in GNU
  169.      Emacs 19; in other versions, all buffers and strings consist of a
  170.      single interval.
  171. `for VAR being the frames'
  172.      This clause iterates over all frames, i.e., X window system windows
  173.      open on Emacs files.  This clause works only under Emacs 19.  The
  174.      clause `screens' is a synonym for `frames'.  The frames are
  175.      visited in `next-frame' order starting from `selected-frame'.
  176. `for VAR being the windows [of FRAME]'
  177.      This clause iterates over the windows (in the Emacs sense) of the
  178.      current frame, or of the specified FRAME.  (In Emacs 18 there is
  179.      only ever one frame, and the `of' term is not allowed there.)
  180. `for VAR being the buffers'
  181.      This clause iterates over all buffers in Emacs.  It is equivalent
  182.      to `for VAR in (buffer-list)'.
  183. `for VAR = EXPR1 then EXPR2'
  184.      This clause does a general iteration.  The first time through the
  185.      loop, VAR will be bound to EXPR1.  On the second and successive
  186.      iterations it will be set by evaluating EXPR2 (which may refer to
  187.      the old value of VAR).  For example, these two loops are
  188.      effectively the same:
  189.           (loop for x on my-list by 'cddr do ...)
  190.           (loop for x = my-list then (cddr x) while x do ...)
  191.      Note that this type of `for' clause does not imply any sort of
  192.      terminating condition; the above example combines it with a
  193.      `while' clause to tell when to end the loop.
  194.      If you omit the `then' term, EXPR1 is used both for the initial
  195.      setting and for successive settings:
  196.           (loop for x = (random) when (> x 0) return x)
  197.      This loop keeps taking random numbers from the `(random)' function
  198.      until it gets a positive one, which it then returns.
  199.    If you include several `for' clauses in a row, they are treated
  200. sequentially (as if by `let*' and `setq').  You can instead use the
  201. word `and' to link the clauses, in which case they are processed in
  202. parallel (as if by `let' and `psetq').
  203.      (loop for x below 5 for y = nil then x collect (list x y))
  204.           => ((0 nil) (1 1) (2 2) (3 3) (4 4))
  205.      (loop for x below 5 and y = nil then x collect (list x y))
  206.           => ((0 nil) (1 0) (2 1) (3 2) (4 3))
  207. In the first loop, `y' is set based on the value of `x' that was just
  208. set by the previous clause; in the second loop, `x' and `y' are set
  209. simultaneously so `y' is set based on the value of `x' left over from
  210. the previous time through the loop.
  211.    Another feature of the `loop' macro is "destructuring", similar in
  212. concept to the destructuring provided by `defmacro'.  The VAR part of
  213. any `for' clause can be given as a list of variables instead of a
  214. single variable.  The values produced during loop execution must be
  215. lists; the values in the lists are stored in the corresponding
  216. variables.
  217.      (loop for (x y) in '((2 3) (4 5) (6 7)) collect (+ x y))
  218.           => (5 9 13)
  219.    In loop destructuring, if there are more values than variables the
  220. trailing values are ignored, and if there are more variables than
  221. values the trailing variables get the value `nil'.  If `nil' is used as
  222. a variable name, the corresponding values are ignored.  Destructuring
  223. may be nested, and dotted lists of variables like `(x . y)' are allowed.
  224. File: cl,  Node: Iteration Clauses,  Next: Accumulation Clauses,  Prev: For Clauses,  Up: Loop Facility
  225. Iteration Clauses
  226. -----------------
  227. Aside from `for' clauses, there are several other loop clauses that
  228. control the way the loop operates.  They might be used by themselves,
  229. or in conjunction with one or more `for' clauses.
  230. `repeat INTEGER'
  231.      This clause simply counts up to the specified number using an
  232.      internal temporary variable.  The loops
  233.           (loop repeat n do ...)
  234.           (loop for temp to n do ...)
  235.      are identical except that the second one forces you to choose a
  236.      name for a variable you aren't actually going to use.
  237. `while CONDITION'
  238.      This clause stops the loop when the specified condition (any Lisp
  239.      expression) becomes `nil'.  For example, the following two loops
  240.      are equivalent, except for the implicit `nil' block that surrounds
  241.      the second one:
  242.           (while COND FORMS...)
  243.           (loop while COND do FORMS...)
  244. `until CONDITION'
  245.      This clause stops the loop when the specified condition is true,
  246.      i.e., non-`nil'.
  247. `always CONDITION'
  248.      This clause stops the loop when the specified condition is `nil'.
  249.      Unlike `while', it stops the loop using `return nil' so that the
  250.      `finally' clauses are not executed.  If all the conditions were
  251.      non-`nil', the loop returns `t':
  252.           (if (loop for size in size-list always (> size 10))
  253.               (some-big-sizes)
  254.             (no-big-sizes))
  255. `never CONDITION'
  256.      This clause is like `always', except that the loop returns `t' if
  257.      any conditions were false, or `nil' otherwise.
  258. `thereis CONDITION'
  259.      This clause stops the loop when the specified form is non-`nil';
  260.      in this case, it returns that non-`nil' value.  If all the values
  261.      were `nil', the loop returns `nil'.
  262. File: cl,  Node: Accumulation Clauses,  Next: Other Clauses,  Prev: Iteration Clauses,  Up: Loop Facility
  263. Accumulation Clauses
  264. --------------------
  265. These clauses cause the loop to accumulate information about the
  266. specified Lisp FORM.  The accumulated result is returned from the loop
  267. unless overridden, say, by a `return' clause.
  268. `collect FORM'
  269.      This clause collects the values of FORM into a list.  Several
  270.      examples of `collect' appear elsewhere in this manual.
  271.      The word `collecting' is a synonym for `collect', and likewise for
  272.      the other accumulation clauses.
  273. `append FORM'
  274.      This clause collects lists of values into a result list using
  275.      `append'.
  276. `nconc FORM'
  277.      This clause collects lists of values into a result list by
  278.      destructively modifying the lists rather than copying them.
  279. `concat FORM'
  280.      This clause concatenates the values of the specified FORM into a
  281.      string.  (It and the following clause are extensions to standard
  282.      Common Lisp.)
  283. `vconcat FORM'
  284.      This clause concatenates the values of the specified FORM into a
  285.      vector.
  286. `count FORM'
  287.      This clause counts the number of times the specified FORM
  288.      evaluates to a non-`nil' value.
  289. `sum FORM'
  290.      This clause accumulates the sum of the values of the specified
  291.      FORM, which must evaluate to a number.
  292. `maximize FORM'
  293.      This clause accumulates the maximum value of the specified FORM,
  294.      which must evaluate to a number.  The return value is undefined if
  295.      `maximize' is executed zero times.
  296. `minimize FORM'
  297.      This clause accumulates the minimum value of the specified FORM.
  298.    Accumulation clauses can be followed by `into VAR' to cause the data
  299. to be collected into variable VAR (which is automatically `let'-bound
  300. during the loop) rather than an unnamed temporary variable.  Also,
  301. `into' accumulations do not automatically imply a return value.  The
  302. loop must use some explicit mechanism, such as `finally return', to
  303. return the accumulated result.
  304.    It is legal for several accumulation clauses of the same type to
  305. accumulate into the same place.  From Steele:
  306.      (loop for name in '(fred sue alice joe june)
  307.            for kids in '((bob ken) () () (kris sunshine) ())
  308.            collect name
  309.            append kids)
  310.           => (fred bob ken sue alice joe kris sunshine june)
  311. File: cl,  Node: Other Clauses,  Prev: Accumulation Clauses,  Up: Loop Facility
  312. Other Clauses
  313. -------------
  314. This section describes the remaining loop clauses.
  315. `with VAR = VALUE'
  316.      This clause binds a variable to a value around the loop, but
  317.      otherwise leaves the variable alone during the loop.  The following
  318.      loops are basically equivalent:
  319.           (loop with x = 17 do ...)
  320.           (let ((x 17)) (loop do ...))
  321.           (loop for x = 17 then x do ...)
  322.      Naturally, the variable VAR might be used for some purpose in the
  323.      rest of the loop.  For example:
  324.           (loop for x in my-list  with res = nil  do (push x res)
  325.                 finally return res)
  326.      This loop inserts the elements of `my-list' at the front of a new
  327.      list being accumulated in `res', then returns the list `res' at
  328.      the end of the loop.  The effect is similar to that of a `collect'
  329.      clause, but the list gets reversed by virtue of the fact that
  330.      elements are being pushed onto the front of `res' rather than the
  331.      end.
  332.      If you omit the `=' term, the variable is initialized to `nil'.
  333.      (Thus the `= nil' in the above example is unnecessary.)
  334.      Bindings made by `with' are sequential by default, as if by
  335.      `let*'.  Just like `for' clauses, `with' clauses can be linked
  336.      with `and' to cause the bindings to be made by `let' instead.
  337. `if CONDITION CLAUSE'
  338.      This clause executes the following loop clause only if the
  339.      specified condition is true.  The following CLAUSE should be an
  340.      accumulation, `do', `return', `if', or `unless' clause.  Several
  341.      clauses may be linked by separating them with `and'.  These
  342.      clauses may be followed by `else' and a clause or clauses to
  343.      execute if the condition was false.  The whole construct may
  344.      optionally be followed by the word `end' (which may be used to
  345.      disambiguate an `else' or `and' in a nested `if').
  346.      The actual non-`nil' value of the condition form is available by
  347.      the name `it' in the "then" part.  For example:
  348.           (setq funny-numbers '(6 13 -1))
  349.                => (6 13 -1)
  350.           (loop for x below 10
  351.                 if (oddp x)
  352.                   collect x into odds
  353.                   and if (memq x funny-numbers) return (cdr it) end
  354.                 else
  355.                   collect x into evens
  356.                 finally return (vector odds evens))
  357.                => [(1 3 5 7 9) (0 2 4 6 8)]
  358.           (setq funny-numbers '(6 7 13 -1))
  359.                => (6 7 13 -1)
  360.           (loop <same thing again>)
  361.                => (13 -1)
  362.      Note the use of `and' to put two clauses into the "then" part, one
  363.      of which is itself an `if' clause.  Note also that `end', while
  364.      normally optional, was necessary here to make it clear that the
  365.      `else' refers to the outermost `if' clause.  In the first case,
  366.      the loop returns a vector of lists of the odd and even values of
  367.      X.  In the second case, the odd number 7 is one of the
  368.      `funny-numbers' so the loop returns early; the actual returned
  369.      value is based on the result of the `memq' call.
  370. `when CONDITION CLAUSE'
  371.      This clause is just a synonym for `if'.
  372. `unless CONDITION CLAUSE'
  373.      The `unless' clause is just like `if' except that the sense of the
  374.      condition is reversed.
  375. `named NAME'
  376.      This clause gives a name other than `nil' to the implicit block
  377.      surrounding the loop.  The NAME is the symbol to be used as the
  378.      block name.
  379. `initially [do] FORMS...'
  380.      This keyword introduces one or more Lisp forms which will be
  381.      executed before the loop itself begins (but after any variables
  382.      requested by `for' or `with' have been bound to their initial
  383.      values).  `initially' clauses can appear anywhere; if there are
  384.      several, they are executed in the order they appear in the loop.
  385.      The keyword `do' is optional.
  386. `finally [do] FORMS...'
  387.      This introduces Lisp forms which will be executed after the loop
  388.      finishes (say, on request of a `for' or `while').  `initially' and
  389.      `finally' clauses may appear anywhere in the loop construct, but
  390.      they are executed (in the specified order) at the beginning or
  391.      end, respectively, of the loop.
  392. `finally return FORM'
  393.      This says that FORM should be executed after the loop is done to
  394.      obtain a return value.  (Without this, or some other clause like
  395.      `collect' or `return', the loop will simply return `nil'.)
  396.      Variables bound by `for', `with', or `into' will still contain
  397.      their final values when FORM is executed.
  398. `do FORMS...'
  399.      The word `do' may be followed by any number of Lisp expressions
  400.      which are executed as an implicit `progn' in the body of the loop.
  401.      Many of the examples in this section illustrate the use of `do'.
  402. `return FORM'
  403.      This clause causes the loop to return immediately.  The following
  404.      Lisp form is evaluated to give the return value of the `loop'
  405.      form.  The `finally' clauses, if any, are not executed.  Of
  406.      course, `return' is generally used inside an `if' or `unless', as
  407.      its use in a top-level loop clause would mean the loop would never
  408.      get to "loop" more than once.
  409.      The clause `return FORM' is equivalent to `do (return FORM)' (or
  410.      `return-from' if the loop was named).  The `return' clause is
  411.      implemented a bit more efficiently, though.
  412.    While there is no high-level way to add user extensions to `loop'
  413. (comparable to `defsetf' for `setf', say), this package does offer two
  414. properties called `cl-loop-handler' and `cl-loop-for-handler' which are
  415. functions to be called when a given symbol is encountered as a
  416. top-level loop clause or `for' clause, respectively.  Consult the
  417. source code in file `cl-macs.el' for details.
  418.    This package's `loop' macro is compatible with that of Common Lisp,
  419. except that a few features are not implemented:  `loop-finish' and
  420. data-type specifiers.  Naturally, the `for' clauses which iterate over
  421. keymaps, overlays, intervals, frames, windows, and buffers are
  422. Emacs-specific extensions.
  423. File: cl,  Node: Multiple Values,  Prev: Loop Facility,  Up: Control Structure
  424. Multiple Values
  425. ===============
  426. Common Lisp functions can return zero or more results.  Emacs Lisp
  427. functions, by contrast, always return exactly one result.  This package
  428. makes no attempt to emulate Common Lisp multiple return values; Emacs
  429. versions of Common Lisp functions that return more than one value
  430. either return just the first value (as in `compiler-macroexpand') or
  431. return a list of values (as in `get-setf-method').  This package *does*
  432. define placeholders for the Common Lisp functions that work with
  433. multiple values, but in Emacs Lisp these functions simply operate on
  434. lists instead.  The `values' form, for example, is a synonym for `list'
  435. in Emacs.
  436.  - Special Form: multiple-value-bind (VAR...) VALUES-FORM FORMS...
  437.      This form evaluates VALUES-FORM, which must return a list of
  438.      values.  It then binds the VARs to these respective values, as if
  439.      by `let', and then executes the body FORMS.  If there are more
  440.      VARs than values, the extra VARs are bound to `nil'.  If there are
  441.      fewer VARs than values, the excess values are ignored.
  442.  - Special Form: multiple-value-setq (VAR...) FORM
  443.      This form evaluates FORM, which must return a list of values.  It
  444.      then sets the VARs to these respective values, as if by `setq'.
  445.      Extra VARs or values are treated the same as in
  446.      `multiple-value-bind'.
  447.    The older Quiroz package attempted a more faithful (but still
  448. imperfect) emulation of Common Lisp multiple values.  The old method
  449. "usually" simulated true multiple values quite well, but under certain
  450. circumstances would leave spurious return values in memory where a
  451. later, unrelated `multiple-value-bind' form would see them.
  452.    Since a perfect emulation is not feasible in Emacs Lisp, this
  453. package opts to keep it as simple and predictable as possible.
  454. File: cl,  Node: Macros,  Next: Declarations,  Prev: Control Structure,  Up: Top
  455. Macros
  456. ******
  457. This package implements the various Common Lisp features of `defmacro',
  458. such as destructuring, `&environment', and `&body'.  Top-level `&whole'
  459. is not implemented for `defmacro' due to technical difficulties.  *Note
  460. Argument Lists::.
  461.    Destructuring is made available to the user by way of the following
  462. macro:
  463.  - Special Form: destructuring-bind ARGLIST EXPR FORMS...
  464.      This macro expands to code which executes FORMS, with the
  465.      variables in ARGLIST bound to the list of values returned by EXPR.
  466.      The ARGLIST can include all the features allowed for `defmacro'
  467.      argument lists, including destructuring.  (The `&environment'
  468.      keyword is not allowed.)  The macro expansion will signal an error
  469.      if EXPR returns a list of the wrong number of arguments or with
  470.      incorrect keyword arguments.
  471.    This package also includes the Common Lisp `define-compiler-macro'
  472. facility, which allows you to define compile-time expansions and
  473. optimizations for your functions.
  474.  - Special Form: define-compiler-macro NAME ARGLIST FORMS...
  475.      This form is similar to `defmacro', except that it only expands
  476.      calls to NAME at compile-time; calls processed by the Lisp
  477.      interpreter are not expanded, nor are they expanded by the
  478.      `macroexpand' function.
  479.      The argument list may begin with a `&whole' keyword and a
  480.      variable.  This variable is bound to the macro-call form itself,
  481.      i.e., to a list of the form `(NAME ARGS...)'.  If the macro
  482.      expander returns this form unchanged, then the compiler treats it
  483.      as a normal function call.  This allows compiler macros to work as
  484.      optimizers for special cases of a function, leaving complicated
  485.      cases alone.
  486.      For example, here is a simplified version of a definition that
  487.      appears as a standard part of this package:
  488.           (define-compiler-macro member* (&whole form a list &rest keys)
  489.             (if (and (null keys)
  490.                      (eq (car-safe a) 'quote)
  491.                      (not (floatp-safe (cadr a))))
  492.                 (list 'memq a list)
  493.               form))
  494.      This definition causes `(member* A LIST)' to change to a call to
  495.      the faster `memq' in the common case where A is a
  496.      non-floating-point constant; if A is anything else, or if there
  497.      are any keyword arguments in the call, then the original `member*'
  498.      call is left intact.  (The actual compiler macro for `member*'
  499.      optimizes a number of other cases, including common `:test'
  500.      predicates.)
  501.  - Function: compiler-macroexpand FORM
  502.      This function is analogous to `macroexpand', except that it
  503.      expands compiler macros rather than regular macros.  It returns
  504.      FORM unchanged if it is not a call to a function for which a
  505.      compiler macro has been defined, or if that compiler macro decided
  506.      to punt by returning its `&whole' argument.  Like `macroexpand',
  507.      it expands repeatedly until it reaches a form for which no further
  508.      expansion is possible.
  509.    *Note Macro Bindings::, for descriptions of the `macrolet' and
  510. `symbol-macrolet' forms for making "local" macro definitions.
  511. File: cl,  Node: Declarations,  Next: Symbols,  Prev: Macros,  Up: Top
  512. Declarations
  513. ************
  514. Common Lisp includes a complex and powerful "declaration" mechanism
  515. that allows you to give the compiler special hints about the types of
  516. data that will be stored in particular variables, and about the ways
  517. those variables and functions will be used.  This package defines
  518. versions of all the Common Lisp declaration forms: `declare',
  519. `locally', `proclaim', `declaim', and `the'.
  520.    Most of the Common Lisp declarations are not currently useful in
  521. Emacs Lisp, as the byte-code system provides little opportunity to
  522. benefit from type information, and `special' declarations are redundant
  523. in a fully dynamically-scoped Lisp.  A few declarations are meaningful
  524. when the optimizing Emacs 19 byte compiler is being used, however.
  525. Under the earlier non-optimizing compiler, these declarations will
  526. effectively be ignored.
  527.  - Function: proclaim DECL-SPEC
  528.      This function records a "global" declaration specified by
  529.      DECL-SPEC.  Since `proclaim' is a function, DECL-SPEC is evaluated
  530.      and thus should normally be quoted.
  531.  - Special Form: declaim DECL-SPECS...
  532.      This macro is like `proclaim', except that it takes any number of
  533.      DECL-SPEC arguments, and the arguments are unevaluated and
  534.      unquoted.  The `declaim' macro also puts an `(eval-when (compile
  535.      load eval) ...)' around the declarations so that they will be
  536.      registered at compile-time as well as at run-time.  (This is vital,
  537.      since normally the declarations are meant to influence the way the
  538.      compiler treats the rest of the file that contains the `declaim'
  539.      form.)
  540.  - Special Form: declare DECL-SPECS...
  541.      This macro is used to make declarations within functions and other
  542.      code.  Common Lisp allows declarations in various locations,
  543.      generally at the beginning of any of the many "implicit `progn's"
  544.      throughout Lisp syntax, such as function bodies, `let' bodies,
  545.      etc.  Currently the only declaration understood by `declare' is
  546.      `special'.
  547.  - Special Form: locally DECLARATIONS... FORMS...
  548.      In this package, `locally' is no different from `progn'.
  549.  - Special Form: the TYPE FORM
  550.      Type information provided by `the' is ignored in this package; in
  551.      other words, `(the TYPE FORM)' is equivalent to FORM.  Future
  552.      versions of the optimizing byte-compiler may make use of this
  553.      information.
  554.      For example, `mapcar' can map over both lists and arrays.  It is
  555.      hard for the compiler to expand `mapcar' into an in-line loop
  556.      unless it knows whether the sequence will be a list or an array
  557.      ahead of time.  With `(mapcar 'car (the vector foo))', a future
  558.      compiler would have enough information to expand the loop in-line.
  559.      For now, Emacs Lisp will treat the above code as exactly equivalent
  560.      to `(mapcar 'car foo)'.
  561.    Each DECL-SPEC in a `proclaim', `declaim', or `declare' should be a
  562. list beginning with a symbol that says what kind of declaration it is.
  563. This package currently understands `special', `inline', `notinline',
  564. `optimize', and `warn' declarations.  (The `warn' declaration is an
  565. extension of standard Common Lisp.)  Other Common Lisp declarations,
  566. such as `type' and `ftype', are silently ignored.
  567. `special'
  568.      Since all variables in Emacs Lisp are "special" (in the Common
  569.      Lisp sense), `special' declarations are only advisory.  They
  570.      simply tell the optimizing byte compiler that the specified
  571.      variables are intentionally being referred to without being bound
  572.      in the body of the function.  The compiler normally emits warnings
  573.      for such references, since they could be typographical errors for
  574.      references to local variables.
  575.      The declaration `(declare (special VAR1 VAR2))' is equivalent to
  576.      `(defvar VAR1) (defvar VAR2)' in the optimizing compiler, or to
  577.      nothing at all in older compilers (which do not warn for non-local
  578.      references).
  579.      In top-level contexts, it is generally better to write `(defvar
  580.      VAR)' than `(declaim (special VAR))', since `defvar' makes your
  581.      intentions clearer.  But the older byte compilers can not handle
  582.      `defvar's appearing inside of functions, while `(declare (special
  583.      VAR))' takes care to work correctly with all compilers.
  584. `inline'
  585.      The `inline' DECL-SPEC lists one or more functions whose bodies
  586.      should be expanded "in-line" into calling functions whenever the
  587.      compiler is able to arrange for it.  For example, the Common Lisp
  588.      function `cadr' is declared `inline' by this package so that the
  589.      form `(cadr X)' will expand directly into `(car (cdr X))' when it
  590.      is called in user functions, for a savings of one (relatively
  591.      expensive) function call.
  592.      The following declarations are all equivalent.  Note that the
  593.      `defsubst' form is a convenient way to define a function and
  594.      declare it inline all at once, but it is available only in Emacs
  595.      19.
  596.           (declaim (inline foo bar))
  597.           (eval-when (compile load eval) (proclaim '(inline foo bar)))
  598.           (proclaim-inline foo bar)      ; Lucid Emacs only
  599.           (defsubst foo (...) ...)       ; instead of defun; Emacs 19 only
  600.      *Note:*  This declaration remains in effect after the containing
  601.      source file is done.  It is correct to use it to request that a
  602.      function you have defined should be inlined, but it is impolite to
  603.      use it to request inlining of an external function.
  604.      In Common Lisp, it is possible to use `(declare (inline ...))'
  605.      before a particular call to a function to cause just that call to
  606.      be inlined; the current byte compilers provide no way to implement
  607.      this, so `(declare (inline ...))' is currently ignored by this
  608.      package.
  609. `notinline'
  610.      The `notinline' declaration lists functions which should not be
  611.      inlined after all; it cancels a previous `inline' declaration.
  612. `optimize'
  613.      This declaration controls how much optimization is performed by
  614.      the compiler.  Naturally, it is ignored by the earlier
  615.      non-optimizing compilers.
  616.      The word `optimize' is followed by any number of lists like
  617.      `(speed 3)' or `(safety 2)'.  Common Lisp defines several
  618.      optimization "qualities"; this package ignores all but `speed' and
  619.      `safety'.  The value of a quality should be an integer from 0 to
  620.      3, with 0 meaning "unimportant" and 3 meaning "very important."
  621.      The default level for both qualities is 1.
  622.      In this package, with the Emacs 19 optimizing compiler, the
  623.      `speed' quality is tied to the `byte-compile-optimize' flag, which
  624.      is set to `nil' for `(speed 0)' and to `t' for higher settings;
  625.      and the `safety' quality is tied to the
  626.      `byte-compile-delete-errors' flag, which is set to `t' for
  627.      `(safety 3)' and to `nil' for all lower settings.  (The latter
  628.      flag controls whether the compiler is allowed to optimize out code
  629.      whose only side-effect could be to signal an error, e.g.,
  630.      rewriting `(progn foo bar)' to `bar' when it is not known whether
  631.      `foo' will be bound at run-time.)
  632.      Note that even compiling with `(safety 0)', the Emacs byte-code
  633.      system provides sufficient checking to prevent real harm from
  634.      being done.  For example, barring serious bugs in Emacs itself,
  635.      Emacs will not crash with a segmentation fault just because of an
  636.      error in a fully-optimized Lisp program.
  637.      The `optimize' declaration is normally used in a top-level
  638.      `proclaim' or `declaim' in a file; Common Lisp allows it to be
  639.      used with `declare' to set the level of optimization locally for a
  640.      given form, but this will not work correctly with the current
  641.      version of the optimizing compiler.  (The `declare' will set the
  642.      new optimization level, but that level will not automatically be
  643.      unset after the enclosing form is done.)
  644. `warn'
  645.      This declaration controls what sorts of warnings are generated by
  646.      the byte compiler.  Again, only the optimizing compiler generates
  647.      warnings.  The word `warn' is followed by any number of "warning
  648.      qualities," similar in form to optimization qualities.  The
  649.      currently supported warning types are `redefine', `callargs',
  650.      `unresolved', and `free-vars'; in the current system, a value of 0
  651.      will disable these warnings and any higher value will enable them.
  652.      See the documentation for the optimizing byte compiler for details.
  653. File: cl,  Node: Symbols,  Next: Numbers,  Prev: Declarations,  Up: Top
  654. Symbols
  655. *******
  656. This package defines several symbol-related features that were missing
  657. from Emacs Lisp.
  658. * Menu:
  659. * Property Lists::       `get*', `remprop', `getf', `remf'
  660. * Creating Symbols::     `gensym', `gentemp'
  661. File: cl,  Node: Property Lists,  Next: Creating Symbols,  Prev: Symbols,  Up: Symbols
  662. Property Lists
  663. ==============
  664. These functions augment the standard Emacs Lisp functions `get' and
  665. `put' for operating on properties attached to symbols.  There are also
  666. functions for working with property lists as first-class data
  667. structures not attached to particular symbols.
  668.  - Function: get* SYMBOL PROPERTY &optional DEFAULT
  669.      This function is like `get', except that if the property is not
  670.      found, the DEFAULT argument provides the return value.  (The Emacs
  671.      Lisp `get' function always uses `nil' as the default; this
  672.      package's `get*' is equivalent to Common Lisp's `get'.)
  673.      The `get*' function is `setf'-able; when used in this fashion, the
  674.      DEFAULT argument is allowed but ignored.
  675.  - Function: remprop SYMBOL PROPERTY
  676.      This function removes the entry for PROPERTY from the property
  677.      list of SYMBOL.  It returns a true value if the property was
  678.      indeed found and removed, or `nil' if there was no such property.
  679.      (This function was probably omitted from Emacs originally because,
  680.      since `get' did not allow a DEFAULT, it was very difficult to
  681.      distinguish between a missing property and a property whose value
  682.      was `nil'; thus, setting a property to `nil' was close enough to
  683.      `remprop' for most purposes.)
  684.  - Function: getf PLACE PROPERTY &optional DEFAULT
  685.      This function scans the list PLACE as if it were a property list,
  686.      i.e., a list of alternating property names and values.  If an
  687.      even-numbered element of PLACE is found which is `eq' to PROPERTY,
  688.      the following odd-numbered element is returned.  Otherwise,
  689.      DEFAULT is returned (or `nil' if no default is given).
  690.      In particular,
  691.           (get sym prop)  ==  (getf (symbol-plist sym) prop)
  692.      It is legal to use `getf' as a `setf' place, in which case its
  693.      PLACE argument must itself be a legal `setf' place.  The DEFAULT
  694.      argument, if any, is ignored in this context.  The effect is to
  695.      change (via `setcar') the value cell in the list that corresponds
  696.      to PROPERTY, or to cons a new property-value pair onto the list if
  697.      the property is not yet present.
  698.           (put sym prop val)  ==  (setf (getf (symbol-plist sym) prop) val)
  699.      The `get' and `get*' functions are also `setf'-able.  The fact
  700.      that `default' is ignored can sometimes be useful:
  701.           (incf (get* 'foo 'usage-count 0))
  702.      Here, symbol `foo''s `usage-count' property is incremented if it
  703.      exists, or set to 1 (an incremented 0) otherwise.
  704.      When not used as a `setf' form, `getf' is just a regular function
  705.      and its PLACE argument can actually be any Lisp expression.
  706.  - Special Form: remf PLACE PROPERTY
  707.      This macro removes the property-value pair for PROPERTY from the
  708.      property list stored at PLACE, which is any `setf'-able place
  709.      expression.  It returns true if the property was found.  Note that
  710.      if PROPERTY happens to be first on the list, this will effectively
  711.      do a `(setf PLACE (cddr PLACE))', whereas if it occurs later, this
  712.      simply uses `setcdr' to splice out the property and value cells.
  713. File: cl,  Node: Creating Symbols,  Prev: Property Lists,  Up: Symbols
  714. Creating Symbols
  715. ================
  716. These functions create unique symbols, typically for use as temporary
  717. variables.
  718.  - Function: gensym &optional X
  719.      This function creates a new, uninterned symbol (using
  720.      `make-symbol') with a unique name.  (The name of an uninterned
  721.      symbol is relevant only if the symbol is printed.)  By default,
  722.      the name is generated from an increasing sequence of numbers,
  723.      `G1000', `G1001', `G1002', etc.  If the optional argument X is a
  724.      string, that string is used as a prefix instead of `G'.
  725.      Uninterned symbols are used in macro expansions for temporary
  726.      variables, to ensure that their names will not conflict with
  727.      "real" variables in the user's code.
  728.  - Variable: *gensym-counter*
  729.      This variable holds the counter used to generate `gensym' names.
  730.      It is incremented after each use by `gensym'.  In Common Lisp this
  731.      is initialized with 0, but this package initializes it with a
  732.      random (time-dependent) value to avoid trouble when two files that
  733.      each used `gensym' in their compilation are loaded together.
  734.      (Uninterned symbols become interned when the compiler writes them
  735.      out to a file and the Emacs loader loads them, so their names have
  736.      to be treated a bit more carefully than in Common Lisp where
  737.      uninterned symbols remain uninterned after loading.)
  738.  - Function: gentemp &optional X
  739.      This function is like `gensym', except that it produces a new
  740.      *interned* symbol.  If the symbol that is generated already
  741.      exists, the function keeps incrementing the counter and trying
  742.      again until a new symbol is generated.
  743.    The Quiroz `cl.el' package also defined a `defkeyword' form for
  744. creating self-quoting keyword symbols.  This package automatically
  745. creates all keywords that are called for by `&key' argument specifiers,
  746. and discourages the use of keywords as data unrelated to keyword
  747. arguments, so the `defkeyword' form has been discontinued.
  748. File: cl,  Node: Numbers,  Next: Sequences,  Prev: Symbols,  Up: Top
  749. Numbers
  750. *******
  751. This section defines a few simple Common Lisp operations on numbers
  752. which were left out of Emacs Lisp.
  753. * Menu:
  754. * Predicates on Numbers::       `plusp', `oddp', `floatp-safe', etc.
  755. * Numerical Functions::         `abs', `expt', `floor*', etc.
  756. * Random Numbers::              `random*', `make-random-state'
  757. * Implementation Parameters::   `most-positive-fixnum', `most-positive-float'
  758. File: cl,  Node: Predicates on Numbers,  Next: Numerical Functions,  Prev: Numbers,  Up: Numbers
  759. Predicates on Numbers
  760. =====================
  761. These functions return `t' if the specified condition is true of the
  762. numerical argument, or `nil' otherwise.
  763.  - Function: plusp NUMBER
  764.      This predicate tests whether NUMBER is positive.  It is an error
  765.      if the argument is not a number.
  766.  - Function: minusp NUMBER
  767.      This predicate tests whether NUMBER is negative.  It is an error
  768.      if the argument is not a number.
  769.  - Function: oddp INTEGER
  770.      This predicate tests whether INTEGER is odd.  It is an error if
  771.      the argument is not an integer.
  772.  - Function: evenp INTEGER
  773.      This predicate tests whether INTEGER is even.  It is an error if
  774.      the argument is not an integer.
  775.  - Function: floatp-safe OBJECT
  776.      This predicate tests whether OBJECT is a floating-point number.
  777.      On systems that support floating-point, this is equivalent to
  778.      `floatp'.  On other systems, this always returns `nil'.
  779. File: cl,  Node: Numerical Functions,  Next: Random Numbers,  Prev: Predicates on Numbers,  Up: Numbers
  780. Numerical Functions
  781. ===================
  782. These functions perform various arithmetic operations on numbers.
  783.  - Function: abs NUMBER
  784.      This function returns the absolute value of NUMBER.  (Newer
  785.      versions of Emacs provide this as a built-in function; this package
  786.      defines `abs' only for Emacs 18 versions which don't provide it as
  787.      a primitive.)
  788.  - Function: expt BASE POWER
  789.      This function returns BASE raised to the power of NUMBER.  (Newer
  790.      versions of Emacs provide this as a built-in function; this
  791.      package defines `expt' only for Emacs 18 versions which don't
  792.      provide it as a primitive.)
  793.  - Function: gcd &rest INTEGERS
  794.      This function returns the Greatest Common Divisor of the arguments.
  795.      For one argument, it returns the absolute value of that argument.
  796.      For zero arguments, it returns zero.
  797.  - Function: lcm &rest INTEGERS
  798.      This function returns the Least Common Multiple of the arguments.
  799.      For one argument, it returns the absolute value of that argument.
  800.      For zero arguments, it returns one.
  801.  - Function: isqrt INTEGER
  802.      This function computes the "integer square root" of its integer
  803.      argument, i.e., the greatest integer less than or equal to the true
  804.      square root of the argument.
  805.  - Function: floor* NUMBER &optional DIVISOR
  806.      This function implements the Common Lisp `floor' function.  It is
  807.      called `floor*' to avoid name conflicts with the simpler `floor'
  808.      function built-in to Emacs 19.
  809.      With one argument, `floor*' returns a list of two numbers: The
  810.      argument rounded down (toward minus infinity) to an integer, and
  811.      the "remainder" which would have to be added back to the first
  812.      return value to yield the argument again.  If the argument is an
  813.      integer X, the result is always the list `(X 0)'.  If the argument
  814.      is an Emacs 19 floating-point number, the first result is a Lisp
  815.      integer and the second is a Lisp float between 0 (inclusive) and 1
  816.      (exclusive).
  817.      With two arguments, `floor*' divides NUMBER by DIVISOR, and
  818.      returns the floor of the quotient and the corresponding remainder
  819.      as a list of two numbers.  If `(floor* X Y)' returns `(Q R)', then
  820.      `Q*Y + R = X', with R between 0 (inclusive) and R (exclusive).
  821.      Also, note that `(floor* X)' is exactly equivalent to `(floor* X
  822.      1)'.
  823.      This function is entirely compatible with Common Lisp's `floor'
  824.      function, except that it returns the two results in a list since
  825.      Emacs Lisp does not support multiple-valued functions.
  826.  - Function: ceiling* NUMBER &optional DIVISOR
  827.      This function implements the Common Lisp `ceiling' function, which
  828.      is analogous to `floor' except that it rounds the argument or
  829.      quotient of the arguments up toward plus infinity.  The remainder
  830.      will be between 0 and minus R.
  831.  - Function: truncate* NUMBER &optional DIVISOR
  832.      This function implements the Common Lisp `truncate' function,
  833.      which is analogous to `floor' except that it rounds the argument
  834.      or quotient of the arguments toward zero.  Thus it is equivalent
  835.      to `floor*' if the argument or quotient is positive, or to
  836.      `ceiling*' otherwise.  The remainder has the same sign as NUMBER.
  837.  - Function: round* NUMBER &optional DIVISOR
  838.      This function implements the Common Lisp `round' function, which
  839.      is analogous to `floor' except that it rounds the argument or
  840.      quotient of the arguments to the nearest integer.  In the case of
  841.      a tie (the argument or quotient is exactly halfway between two
  842.      integers), it rounds to the even integer.
  843.  - Function: mod* NUMBER DIVISOR
  844.      This function returns the same value as the second return value of
  845.      `floor'.
  846.  - Function: rem* NUMBER DIVISOR
  847.      This function returns the same value as the second return value of
  848.      `truncate'.
  849.    These definitions are compatible with those in the Quiroz `cl.el'
  850. package, except that this package appends `*' to certain function names
  851. to avoid conflicts with existing Emacs 19 functions, and that the
  852. mechanism for returning multiple values is different.
  853. File: cl,  Node: Random Numbers,  Next: Implementation Parameters,  Prev: Numerical Functions,  Up: Numbers
  854. Random Numbers
  855. ==============
  856. This package also provides an implementation of the Common Lisp random
  857. number generator.  It uses its own additive-congruential algorithm,
  858. which is much more likely to give statistically clean random numbers
  859. than the simple generators supplied by many operating systems.
  860.  - Function: random* NUMBER &optional STATE
  861.      This function returns a random nonnegative number less than
  862.      NUMBER, and of the same type (either integer or floating-point).
  863.      The STATE argument should be a `random-state' object which holds
  864.      the state of the random number generator.  The function modifies
  865.      this state object as a side effect.  If STATE is omitted, it
  866.      defaults to the variable `*random-state*', which contains a
  867.      pre-initialized `random-state' object.
  868.  - Variable: *random-state*
  869.      This variable contains the system "default" `random-state' object,
  870.      used for calls to `random*' that do not specify an alternative
  871.      state object.  Since any number of programs in the Emacs process
  872.      may be accessing `*random-state*' in interleaved fashion, the
  873.      sequence generated from this variable will be irreproducible for
  874.      all intents and purposes.
  875.  - Function: make-random-state &optional STATE
  876.      This function creates or copies a `random-state' object.  If STATE
  877.      is omitted or `nil', it returns a new copy of `*random-state*'.
  878.      This is a copy in the sense that future sequences of calls to
  879.      `(random* N)' and `(random* N S)' (where S is the new random-state
  880.      object) will return identical sequences of random numbers.
  881.      If STATE is a `random-state' object, this function returns a copy
  882.      of that object.  If STATE is `t', this function returns a new
  883.      `random-state' object seeded from the date and time.  As an
  884.      extension to Common Lisp, STATE may also be an integer in which
  885.      case the new object is seeded from that integer; each different
  886.      integer seed will result in a completely different sequence of
  887.      random numbers.
  888.      It is legal to print a `random-state' object to a buffer or file
  889.      and later read it back with `read'.  If a program wishes to use a
  890.      sequence of pseudo-random numbers which can be reproduced later
  891.      for debugging, it can call `(make-random-state t)' to get a new
  892.      sequence, then print this sequence to a file.  When the program is
  893.      later rerun, it can read the original run's random-state from the
  894.      file.
  895.  - Function: random-state-p OBJECT
  896.      This predicate returns `t' if OBJECT is a `random-state' object,
  897.      or `nil' otherwise.
  898.